import { PROJECT_KEY } from '@/config';
import { useTokenStore, usePermissionStore } from '@glz/utils';
import { createRouter, createWebHistory , type RouteRecordRaw } from 'vue-router'

// 使用类型别名定义 RouteRecordRaw
// type RouteRecordRaw = import('vue-router').RouteRecordRaw;

//const main = '@/views/Main.vue'

//路由配對會在當前層級往上找匹配的路由

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'main',
    component: () => import('@/views/Main.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/Home.vue')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/user/User.vue'),
        children:[
          {
            path:'/user/User_edit',
            name:'user_edit',
            component:() => import('@/views/user/User_edit.vue'),
          },
          {
            path: "/user/405", //  可以寫成 "/405" ， 只是結構跟頂層一致，不要區分
            name: 'user_405',
            component: () => import('@/views/405.vue'),
          }
        ]
      }, 
      {
        path: "/NoPermission",
        name: 'NoPermission',
        component: () => import('@/views/NoPermission.vue'),
      },
      {
        path: "/:pathMatch(.*)*",
        name: 'NotFound',
        redirect: "/404",
      },
      {
        path: "/404",
        name: '404',
        component: () => import('@/views/404.vue'),
      },
      {
        path: "/405",
        name: '405',
        component: () => import('@/views/405.vue'),
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/Login.vue')
  },
  {
    path: '/vite-js/:page*', // vue-router@4.x path的写法为：'/my-page/:page*'
    name: 'vite-js',
    component: () => import('@/views/Main.vue')
  }, 
  {
    path: '/vite-ts/:page*', // vue-router@4.x path的写法为：'/my-page/:page*'
    name: 'vite-ts',
    component: () => import('@/views/Main.vue')
  }, 
  {
    path: '/vue-js/:page*', // vue-router@4.x path的写法为：'/my-page/:page*'
    name: 'vue-js',
    component: () => import('@/views/Main.vue')
  },
  {
    path: '/nuxt-ts/:page*', // vue-router@4.x path的写法为：'/my-page/:page*'
    name: 'nuxt-ts',
    component: () => import('@/views/Main.vue')
  },
  {
    path: "/NoNetwork",
    name: 'NoNetwork',
    component: () => import('@/views/NoNetwork.vue'),
  }
  // {
  //   path: '/sub-vue-js/:page*', // vue-router@4.x path的写法为：'/my-page/:page*'
  //   name: 'sub-vue-js',
  //   component: () => import('@/views/Main.vue')
  // },
  // {
  //   path: '/module/:app*', // vue-router@4.x path的写法为：'/my-page/:page*'
  //   name: 'app',
  //   component: () => import('../views/Main.vue')
  // },
  // {
  //   path: '/module/:app2*', // vue-router@4.x path的写法为：'/my-page/:page*'
  //   name: 'app2',
  //   component: () => import('../views/Main.vue')
  // },
  // {
  //   path: '/login',
  //   name: 'login',
  //   component: () => import('@/views/Login.vue')
  // }
]


const router = createRouter({
  history: createWebHistory('/'),
  routes
});

let isfirst = true //臨時字段，標識是否第一次加載路由

router.beforeEach((to, from, next) => {

  //const token = localStorage.getItem('token');
  const tokenInfo = useTokenStore(PROJECT_KEY)
  const token = tokenInfo.token
  console.log("token",token)
  if (!token && to.path !== '/login') {
    // 沒登入且非 login 頁 → 強制跳轉 login
    return next('/login');
  }

  if (token && to.path === '/login') {
    // 已登入還想去 login → 自動導向主頁
    return next('/home');
  }

  console.log('isfirst', isfirst)

  if(isfirst){
  
    dynamicData();

    isfirst = false;

    next({ ...to, replace: true })
  }else{
    next(); // 放行
  }
});

const dynamicData = () => {

  // 1. 动态导入 routes 目录下所有路由模块
  const routeModules = import.meta.glob('./routes/*.ts', { eager: true })

  // 2. 提取所有默认导出的路由
  const dynamicRoutes: RouteRecordRaw[] = []
  for (const path in routeModules) {
    const mod = routeModules[path] as any
    // 支持 default 导出为单个 route 或数组
    if (Array.isArray(mod.default)) {
      dynamicRoutes.push(...mod.default)
    } else {
      dynamicRoutes.push(mod.default)
    }
  }

  console.log("dynamicData", dynamicData)

  let permissionInfo = usePermissionStore()
  let permissionList = permissionInfo.permission



   console.log("permissionList", permissionList)

}




export default router;